package com.lagou.edu.mvcframwork.servlet;

import com.lagou.edu.mvcframwork.annotation.LagouAutowried;
import com.lagou.edu.mvcframwork.annotation.LagouController;
import com.lagou.edu.mvcframwork.annotation.LagouRequestMapping;
import com.lagou.edu.mvcframwork.annotation.LagouService;
import com.lagou.edu.mvcframwork.pojo.Handler;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @Description:
 */
public class LgDispatcherServlet extends HttpServlet {

    private final Properties properties = new Properties();

    private final List<String> classNames = new ArrayList<>();

    private final Map<String, Object> ioc = new HashMap<>();

    private final Map<String, Handler> requestMapping = new HashMap<>();

    @Override
    public void init(ServletConfig config) throws ServletException {
//        super.init(config);
        //加载配置文件 springmvc.properties
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);
        //扫描相关的类，扫描注解
        doScan(properties.getProperty("scanPackage"));

        //初始化bean对象（实现ioc容器，基于注解）
        doInstance();

        //实现依赖注入
        doAutoWired();

        //构造一个heanlerMapping处理映射器，将配置好的url和Method建立映射关系
        initHandlerMapping();

        System.out.println("lagou mvc 初始化完成......");
        //等待请求进入，处理请求
    }

    private void initHandlerMapping() {
        //构建映射关系
        Object bean;
        Class<?> beanClass;
        for (Map.Entry<String, Object> entry : ioc.entrySet()) {
            bean = entry.getValue();
            beanClass = bean.getClass();
            if (!beanClass.isAnnotationPresent(LagouController.class)) continue;
            String baseUrl = "";
            if (beanClass.isAnnotationPresent(LagouRequestMapping.class)) {
                baseUrl = beanClass.getAnnotation(LagouRequestMapping.class).value();
            }
            Method[] methods = beanClass.getMethods();
            for (Method method : methods) {
                if (!method.isAnnotationPresent(LagouRequestMapping.class)) continue;
                LagouRequestMapping annotation = method.getAnnotation(LagouRequestMapping.class);
                String value = annotation.value();
                String uri = baseUrl + value;
                if (requestMapping.containsKey(uri)) {
                    throw new IllegalArgumentException(uri + "uri重复");
                }
                Handler handler = new Handler(bean, method, Pattern.compile(uri), new HashMap<>());

                //处理方法参数
                Parameter[] parameters = method.getParameters();
                for (int i = 0; i < parameters.length; i++) {
                    Parameter parameter = parameters[i];
                    if (parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) {
                        handler.getParamIndexMapping().put(parameter.getType().getSimpleName(),i);
                    } else {
                        handler.getParamIndexMapping().put(parameter.getType().getName(),i);
                    }
                }
                requestMapping.put(uri, handler);
            }
        }

    }

    //实现依赖注入
    private void doAutoWired() {
        //遍历ioc对象中的属性，有autowire的注解，则注入
        String beanName = null;
        Object bean = null;
        try {
            for (Map.Entry<String, Object> entry : ioc.entrySet()) {
                bean = entry.getValue();
                Field[] fields = bean.getClass().getDeclaredFields();
                for (Field field : fields) {
                    //如果字段上有Autowrie属性，则注入
                    if (!field.isAnnotationPresent(LagouAutowried.class)) continue;
                    LagouAutowried annotation = field.getAnnotation(LagouAutowried.class);
                    String value = annotation.value();
                    if ("".equals(value.trim())) {
                        beanName = field.getType().getName();
                    } else {
                        beanName = value;
                    }
                    field.setAccessible(true);
                    if (Objects.nonNull(field.get(bean))) continue;

                    field.set(bean, ioc.get(beanName));
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            System.out.println("bean:" + bean.getClass().getName() + "的属性：" + beanName + "赋值失败");
        }

    }

    //ioc容器
    private void doInstance() {
        try {
            for (String className : classNames) {
                Class<?> aClass = Class.forName(className);
                if (aClass.isAnnotationPresent(LagouController.class)) {
                    String simpleName = aClass.getSimpleName();
                    String lowerFirstSimpleName = lowerName(simpleName);
                    Object o = aClass.newInstance();
                    ioc.put(lowerFirstSimpleName, o);
                } else if (aClass.isAnnotationPresent(LagouService.class)) {
                    LagouService annotation = aClass.getAnnotation(LagouService.class);
                    String value = annotation.value();
                    String beanName = null;
                    Object o = aClass.newInstance();
                    if ("".equals(value.trim())) {
                        beanName = lowerName(aClass.getSimpleName());
                        ioc.put(beanName, o);
                    } else {
                        ioc.put(value, o);
                    }
                    //service是面向接口开发，所以再以接口为beanname，便于以类型注入
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (Class<?> anInterface : interfaces) {
                        //接口以全限定类名做beanName
                        ioc.put(anInterface.getName(), o);
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    private String lowerName(String simpleName) {
        char[] chars = simpleName.toCharArray();
        if ('A' <= chars[0] || 'Z' >= chars[0]) {
            chars[0] += 32;
        }
        return new String(chars);
    }

    private void doScan(String scanPackage) {
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
        System.out.println(scanPackagePath);
        File pack = new File(scanPackagePath);

        File[] files = pack.listFiles();

        for (File file : files) {
            if (file.isDirectory()) {
                doScan(scanPackage + "." + file.getName());
            } else if (file.getName().endsWith(".class")) {
                String className = scanPackage + "." + file.getName().replace(".class", "");
                classNames.add(className);
            }

        }
    }

    //加载配置文件
    private void doLoadConfig(String contextConfigLocation) {

        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //接收处理请求
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    //
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        if(!requestMapping.containsKey(uri)){
            resp.getWriter().write("404 not found !!!");
            return;
        }
        Handler handler = requestMapping.get(uri);

        //获取方法的参数
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
        // 以下就是为了向参数数组中塞值，而且还得保证参数的顺序和方法中形参顺序一致
        Map<String, String[]> parameterMap = req.getParameterMap();
        // 根据上述数组长度创建一个新的数组（参数数组，是要传入反射调用的）
        Object[] paraValues = new Object[parameterTypes.length];
        // 遍历request中所有参数  （填充除了request，response之外的参数）
        for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
            String value = StringUtils.join(Arrays.asList(param.getValue()), ",");

            //如果参数和方法中的参数匹配上了,填充数据
            if(handler.getParamIndexMapping().containsKey(param.getKey())) continue;

            //方法形参确实有该参数,找到他的索引位置,对应的把参数值放到paraValues
            Integer index = handler.getParamIndexMapping().get(param.getKey());

            paraValues[index]=value;
        }
        Integer requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        paraValues[requestIndex]= req;

        Integer responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        paraValues[requestIndex]=resp;

        try {
            handler.getMethod().invoke(handler.getController(),paraValues);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}
